<?php
/**
 * Notes:
 * User: wudg <544038230@qq.com>
 * Date: 2025/3/31 14:18
 */

namespace App\Utils;


use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Context\ApplicationContext;

class RequestHeaderUtil
{
    /**
     * 获取客户端IP
     * @return mixed|string
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public static function getClientIp()
    {
        $request = ApplicationContext::getContainer()->get(RequestInterface::class);
        $headers = $request->getHeaders();

        if (isset($headers['x-forwarded-for'][0]) && !empty($headers['x-forwarded-for'][0])) {
            return $headers['x-forwarded-for'][0];
        } elseif (isset($headers['x-real-ip'][0]) && !empty($headers['x-real-ip'][0])) {
            return $headers['x-real-ip'][0];
        }
        $serverParams = $request->getServerParams();
        return $serverParams['remote_addr'] ?? '';
    }


    /**
     * 获取浏览器信息
     * @return array
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public static function getBrowserAndOs()
    {
        $request = ApplicationContext::getContainer()->get(RequestInterface::class);
        $agent = $request->getHeader('user-agent')[0] ?? null;
        if (!empty($agent)) {

            $br = self::getBrowser($agent);
            $os = self::getOs($agent);
            return [$br,$os];
        } else {
            return ["unknown","unknown"];
        }
    }

    protected static function getBrowser($agent)
    {
        if (preg_match('/MSIE/i', $agent)) {
            $br = 'MSIE';
        } elseif (preg_match('/Firefox/i', $agent)) {
            $br = 'Firefox';
        } elseif (preg_match('/Chrome/i', $agent)) {
            $br = 'Chrome';
        } elseif (preg_match('/Safari/i', $agent)) {
            $br = 'Safari';
        } elseif (preg_match('/Opera/i', $agent)) {
            $br = 'Opera';
        } else {
            $br = 'Other';
        }
        return $br;
    }


    protected static function getOs($agent)
    {
        if (preg_match('/win/i', $agent)) {
            $os = 'Windows';
        } else if (preg_match('/mac/i', $agent)) {
            $os = 'MAC';
        } else if (preg_match('/linux/i', $agent)) {
            $os = 'Linux';
        } else if (preg_match('/unix/i', $agent)) {
            $os = 'Unix';
        } else if (preg_match('/bsd/i', $agent)) {
            $os = 'BSD';
        } else {
            $os = 'Other';
        }
        return $os;
    }
}